#!/bin/sh

. "$TEST_SHELL_PATH/abstract-dbops"

RUN_SCRIPT_PATH="$PROJECT_PATH/src/main/resources/templates/run-pgbench.sh"
SET_RESULT_SCRIPT_PATH="$PROJECT_PATH/src/main/resources/templates/set-pgbench-result.sh"
PATRONI_CONTAINER_NAME=patroni
OP_NAME=pgbench
NORMALIZED_OP_NAME='pgbench'
KEBAB_OP_NAME='pgbench'
POD_0_RESTARTED=false
POD_1_RESTARTED=false
PATRONI_CONTAINER_NAME=patroni
READ_WRITE=true
DURATION=10
POSTGRES_MAJOR_VERSION=12

shell_unit_test_dbops_init() {
  cp "$TEST_SHELL_PATH/dbops-pgbench/pgbench.log.out" "$SHARED_PATH/pgbench_log.1"
}

shell_unit_test_dbops_pgbench() {
  shell_unit_test_dbops
}

shell_unit_test_skip() {
  if [ -z "$IMAGE_NAME" ] && echo "$IMAGE_NAME" | grep "patroni"
  then
    return 0;
  else
    return 1;
  fi
}

mock kubectl kubectl_mock

kubectl_mock() {
  mokked
  case "$*" in
    ("get $DBOPS_CRD_NAME -n $CLUSTER_NAMESPACE $DBOPS_NAME -o json")
      echo '{
        "apiVersion": "stackgres.io/v1",
        "kind": "SGDbOps",
        "metadata": {
          "name": "'"$DBOPS_NAME"'",
          "namespace": "'"$CLUSTER_NAMESPACE"'",
          "resourceVersion": "1",
          "uid": "172381f8-3f37-46c9-9a29-8284a73d1e5e"
        },
        "spec": {
          "sgCluster": "'"$CLUSTER_NAME"'",
          "op": "benchmark",
          "benchmark": {
            "type": "pgbench",
            "pgbench": {
              "databaseSize": "64Mi",
              "duration": "PT10S"
            }
          }
        }
      }'
    ;;
    ("patch $DBOPS_CRD_NAME -n $CLUSTER_NAMESPACE $DBOPS_NAME "*)
    ;;
    ("create --raw /api/v1/namespaces/test/events -f -")
    ;;
    *)
    not_mokked
    ;;
  esac
}

mock psql psql_mock

psql_mock() {
  mokked
  case "$*" in
    ("-q -c CREATE DATABASE "*)
    ;;
    ("-q -c SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '"*"' AND pid != pg_backend_pid() -c DROP DATABASE "*)
    ;;
    ("-q -t -A -c SELECT EXISTS (SELECT * FROM pg_database WHERE datname = '"*"')")
    ;;
    ("-q -t -A -d "*" -c SELECT NOT EXISTS (SELECT * FROM pg_stat_replication WHERE replay_lsn != pg_current_wal_lsn())")
    printf t
    ;;
    *)
    not_mokked
    ;;
  esac
}

mock pgbench pgbench_mock

pgbench_mock() {
  mokked
  case "$*" in
    ("-b select-only -M  -s  -T 10 -c  -j  -r -P 1 -l --sampling-rate "*)
    cat "$TEST_SHELL_PATH/dbops-pgbench/pgbench.out"
    ;;
    ("-b tpcb-like -M  -s  -T 10 -c  -j  -r -P 1 -l --sampling-rate "*)
    cat "$TEST_SHELL_PATH/dbops-pgbench/pgbench.out"
    ;;
    ("-s  -i "*)
    cat "$TEST_SHELL_PATH/dbops-pgbench/pgbench-init.out"
    ;;
    *)
    not_mokked
    ;;
  esac
}

mock python python_mock

python_mock() {
  mokked
  case "$*" in
    ("-c "*"from hdrh.histogram import HdrHistogram"*)
    echo 'HISTFAAAACl4nJNpmSzMwMDAxQABzFCaEUzOmNZg/wEi0NzIyPSYlWmpGBMAh4gG4A=='
    ;;
    *)
    not_mokked
    ;;
  esac
}
